package com.logicbus.redis.xscript;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Pair;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.logicbus.redis.client.Client;
import com.logicbus.redis.toolkit.InfoTool;

import java.util.ArrayList;
import java.util.List;

/**
 * 获取redis信息
 *
 * @since 1.6.12.56 [20191226] <br>
 */
public class RedisInfo extends AbstractLogiclet {
    protected String pid = "$redis-client";
    protected String prefix = "redis_";
    protected String $section = "all";
    public RedisInfo(String tag, Logiclet p) {
        super(tag, p);
    }

    @Override
    public void configure(Properties p){
        super.configure(p);

        pid = PropertiesConstants.getString(p,"pid",pid,true);
        prefix = PropertiesConstants.getString(p,"prefix",prefix);
        $section = PropertiesConstants.getString(p,"section",$section);
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx,
                             ExecuteWatcher watcher) {
        Client client = ctx.getObject(pid);
        if (client != null){
            InfoTool infoTool = (InfoTool) client.getToolKit(InfoTool.class);
            List<Pair<String,String>> result = new ArrayList<Pair<String,String>>();
            infoTool.info(PropertiesConstants.transform(ctx,$section,"all"),result);
            for (Pair<String,String> p:result){
                ctx.SetValue(String.format("%s%s",prefix,p.key()),p.value());
            }
        }
    }
}
